<script>
export default {
  name: "CountBox",
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      timerId: null,
      displayValue: this.value.toString()
    }
  },
  watch: {
    value(newVal) {
      // 父组件值变化时同步显示值
      this.displayValue = newVal.toString()
    }
  },
  methods: {
    reduce() {
      if (this.value <= 1) return
      this.$emit("input", this.value - 1)
    },
    add() {
      this.$emit("input", this.value + 1)
    },
    handle(e) {
      clearTimeout(this.timerId)
      const rawValue = e.detail.value

      // 立即更新显示值（中间状态）
      this.displayValue = rawValue

      this.timerId = setTimeout(() => {
        const num = +rawValue

        if (!Number.isInteger(num) || num <= 0) {
          // 显示值回退，通过中间变量实现状态回退
          return this.displayValue = this.value.toString()
        }

        // 正常提交时更新父组件
        if (num !== this.value) {
          this.$emit('input', num)
        }
        this.timerId = null
      }, 500)
    }
  },
}
</script>

<template>
  <div class="countBox">
    <div @click="reduce" class="reduce">-</div>
    <!-- 修改后模板 -->
    <input
        @input="handle"
        :value="displayValue"
    >
    <div @click="add" class="add">+</div>
  </div>
</template>

<style lang="less">
.countBox {
  display: flex;

  .reduce, .add, input {
    width: 30px;
    height: 30px;
    line-height: 30px;
    background-color: #efefef;
    text-align: center;
  }

  input {
    background-color: #efefef;
    border: 0;
    margin: 0 5px;
    outline: none;
  }
}
</style>
